package springboot.demo.util;


import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ExportExcel {
    public static ByteArrayOutputStream export(HttpServletResponse response) {
        // 模拟数据
        List<String[]> data = new ArrayList<>();
        data.add(new String[]{"姓名", "年龄", "性别"});
        data.add(new String[]{"张三", "25", "男"});
        data.add(new String[]{"李四", "23", "女"});

        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 填充数据
        int rowNum = 0;
        for (String[] rowData : data) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for (String cellData : rowData) {
                Cell cell = row.createCell(colNum++);
                cell.setCellValue(cellData);
            }
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // 导出 Excel 文件
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader("Content-Disposition", "attachment; filename=users.xlsx");
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return baos;
    }
}